package com.zqr.thread;

import com.zqr.utils.Utils;
import lombok.extern.slf4j.Slf4j;


/**
 * 线程中断测试
 */
@Slf4j
public class ThreadInteruptedDemo {
    public static void main(String[] args) {
//        demo1();
        demo2();
    }

    //正常的中断
    public static void demo1(){
        new Thread(() -> {
            Thread.currentThread().interrupt(); //打上中断标记
            log.info("线程实例对象的中断标志位判断结果：{}", Thread.currentThread().isInterrupted()); //true
            log.info("线程类的中断标志位第一次判断结果：{}", Thread.interrupted()); //true
            log.info("线程类的中断标志位第二次判断结果：{}", Thread.interrupted()); //false
        }).start();
    }

    //中断后在异常里面判断中断标志位
    public static void demo2(){
        Runnable r = () -> {
            //线程没被中断的时候继续运行
            while (!Thread.currentThread().isInterrupted()){
                try {
                    log.info("{} thread is running ...", Thread.currentThread().getName());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.info("{} thread is interrupted, it will stop", Thread.currentThread().getName());
                    log.info("{} thread interrupted state: {}", Thread.currentThread().getName(), Thread.currentThread().isInterrupted());
                    //重置标志位,退出while循环
                    Thread.currentThread().interrupt();
                }
            }
        };

        Thread t1 = new Thread(r);
        t1.start();
        log.info("一秒后将会对t1进行中断");
        Utils.sleepIgnoreExp(1000);
        t1.interrupt();
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("{} thread is over, state:{}", t1.getName(), t1.getState());

    }
}
